package f.h.dragon.patterns.mapper;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

/**
 * JdbcTemplate: the Template of Jdbc
 *
 * @author Wenlong Meng(wenlong.meng@gmail.com)
 * @version 1.0 at 2012/04/23
 * @since 1.0
 */
public class JdbcTemplate {
	
	//local variables
	/**
	 * data source
	 */
	private DataSource ds;
	/**
	 * logger
	 */
	private Logger logger = Logger.getLogger(JdbcTemplate.class);
	
	//Constructor
	/**
	 * Construct JdbcTemplate with ds
	 * 
	 * @param ds
	 */
	public JdbcTemplate(DataSource ds) {
		this.ds = ds;
	}
	
	//Logic
	/**
	 * query for list
	 * 
	 * @param <T>
	 * @param mapper
	 * @return
	 */
	public <T> List<T> queryForList(String sql, DataMapper<T> mapper){
		logger.debug("exec: queryForList(" + sql + "," + mapper + ")");
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = ds.getConnection().prepareStatement(sql);
			rs = ps.executeQuery();
			List<T> list = new ArrayList<T>();
			while(rs.next()){
				list.add(mapper.mapRow(rs));
			}
			return list;
		} catch (SQLException e) {
			logger.error(e);
			throw new RuntimeException(e);
		}finally{
			if(ps != null){
				try {
					ps.close();
				} catch (SQLException e) {
					logger.error(e);
				}
			}
			if(rs != null){
				try {
					rs.close();
				} catch (SQLException e) {
					logger.error(e);
				}
			}
		}
	}
	
}
